package com.data.aspect;

import com.data.config.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author ytj
 * @date 2024/4/19
 */
@Slf4j
@Component
@Aspect
@Order(-1)
public class DataSourceAspect {

    @Pointcut("@annotation(com.data.aspect.DataSource)")
    public void dataSourcePointCut(){

    }

    @Around("dataSourcePointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
        MethodSignature methodSignature=(MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        String tenantId=dataSource.value();
        //通过注解方式设置数据源，也可以通过拦截器在方法执行前依据租户信息设置数据源
        DynamicDataSourceContextHolder.removeDataSource();
        if(StringUtils.isBlank(tenantId)){
            DynamicDataSourceContextHolder.setDataSource(DynamicDataSourceContextHolder.DEFAULT_DATASOURCE);
        }else{
            DynamicDataSourceContextHolder.setDataSource(tenantId);
        }
        return joinPoint.proceed();
    }
}
